//
//  StatisticsListViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/12/6.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "StatisticsListViewController.h"
#import "DutyDropListModel.h"
#import "StatisticsTableViewCell.h"
#import "SummarizingListModel.h"
#import "InfoListTableViewCell.h"
#import "DepartmentListViewController.h"
#import "ManageStrutureModel.h"
#import "PersonSelectViewController.h"
#import "AddressSearchModel.h"
#import "CenterLabelTableViewCell.h"
#import "PersonInfoDetailViewController.h"

#define getDropList @"getDropList"//获取可选项列表
#define getSummarizingList @"getSummarizingList"//获取汇总信息
#define getDepartEmpName @"getDepartEmpName"//模糊查询条件

#define TEXTMESSAGE @"请输入部门名称或员工姓名"//搜索提示语


@interface StatisticsListViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
{
    NSMutableArray *_buttonArr;//保存button
    UITableView *_tableView;//列表
    NSInteger _selectButton;//用户当前操作的button
    UITableView *_searchTableView;//搜索结果列表
    AddressSearchModel *_searchListModel;//搜索结果列表model
    UIView *_searchBackView;//搜索view
}
@property (nonatomic,strong)NSMutableArray *itemArr;//保存用户的选择条件
@property (nonatomic,strong)NSString *depOrEmp;//是否是部门
@property (nonatomic,strong)NSString *empId;//员工id

@property (nonatomic,strong)SummarizingListModel *summarzingListModel;//汇总信息
@property (nonatomic,strong)NSMutableDictionary *summarzingDict;
@property (nonatomic,strong)UIView *tableBackView;
@property (nonatomic,strong)UITextField *searchTextField;
@property (nonatomic,strong)NSArray *dateArr;//时间数组
@property (nonatomic,strong)UIScrollView *backScrollView;//滚动视图
@property (nonatomic,strong)DutyDropListModel *dropListModel;//可选择列表
@property (nonatomic,strong)UITableView *infoTableView;//详情tableView
@end

@implementation StatisticsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setRightBackNavigation];
    [self setLeftBackNavigation];
    [self setNavigationTitle:self.navaTitle?self.navaTitle:@"多部门汇总"];
    [self getDropListRequestWithdataSwith:@"2"];
    //默认为本月
    if (self.beginStr==nil||self.endStr==nil) {
        self.beginStr=[LZXHelper getFirstDayInMonth];
        self.endStr=[LZXHelper getLastDayInMonth];
    }
    [self getSummarizingListRequest];
    [self creatView];
    // Do any additional setup after loading the view.
}

- (void)creatView{
     _buttonArr=[NSMutableArray new];
    self.dateArr=@[@"本月",@"上月",@"本季度",@"上季度",@"上半年",@"下半年"];
    //searchView背景
    UIView *searchView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 80)];
    [self.view addSubview:searchView];
    
    _searchTextField=[[UITextField alloc]initWithFrame:CGRectMake(10, 5, IPHONE_WIDTH-20, 30)];        //_spendTextField.color=COLOR_BACKGROUND_GRAY;
    _searchTextField.textAlignment=NSTextAlignmentLeft;
    _searchTextField.delegate=self;
    _searchTextField.font=FONT_14;
    _searchTextField.placeholder=TEXTMESSAGE;
    _searchTextField.backgroundColor=COLOR_BACKGROUND_GRAY;
    //_searchTextField.keyboardType=UIKeyboardTypeNumberPad;
    [searchView addSubview:_searchTextField];
    
    //放大镜
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame=CGRectMake(IPHONE_WIDTH-20-20, 0, 15, 40);
    searchBtn.tag=160;
    [searchBtn setImage:[UIImage imageNamed:@"icon_3_n@2x"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
    [searchView addSubview:searchBtn];
    //分割线
    UILabel *line1=[[UILabel alloc]initWithFrame:CGRectMake(0, 40, IPHONE_WIDTH, 1)];
    line1.backgroundColor=BACKCOLOR_GRAY;
    [searchView addSubview:line1];
    
    //设置检索按钮
    NSArray *titleArr=@[@"筛选",@"本月",@"全部",@"切换"];
    
    for (int i=0; i<titleArr.count; i++) {
        UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(IPHONE_WIDTH/titleArr.count*i, 40, IPHONE_WIDTH/titleArr.count, 40)];
        button.tag=100+i;
        [button setTitle:titleArr[i] forState:UIControlStateNormal];
        //设置图片
        if (i==0) {
            [button setImage:[UIImage imageNamed:@"k_ic_sx@2x"] forState:UIControlStateNormal];

        }else if (i==1||i==2){
            [button setImage:[UIImage imageNamed:@"k_ic_xl@2x"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"k_ic_sl@2x"] forState:UIControlStateSelected];
        }else{
            [button setImage:[UIImage imageNamed:@"k_ic_qh@2x"] forState:UIControlStateNormal];
        }
        //谁知图片和文字的位置
        button.imageEdgeInsets=UIEdgeInsetsMake(10, button.width-20, 10, 0);
        button.titleEdgeInsets=UIEdgeInsetsMake(10, 5, 10, 25);
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //[button setTitleColor:COLOR_SKYBLUE forState:UIControlStateSelected];
        //button.backgroundColor=[UIColor redColor];
        button.titleLabel.font=FONT_14;
        //        [button setTitleColor:COLOR_MIDBLUE forState:UIControlStateSelected];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [searchView addSubview:button];
        [_buttonArr addObject:button];
        
        if (i<titleArr.count-1) {
            UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(IPHONE_WIDTH/titleArr.count*(i+1), 50, 1, 20)];
            line.backgroundColor=BACKCOLOR_GRAY;
            [searchView addSubview:line];
        }
    }
    
    //分割线
    UILabel *line2=[[UILabel alloc]initWithFrame:CGRectMake(0, 79, IPHONE_WIDTH, 1)];
    line2.backgroundColor=BACKCOLOR_GRAY;
    [searchView addSubview:line2];
}

#pragma mark -考勤信息按钮
- (void)creatFunctionButtonView{
    if (self.backScrollView) {
        return;
    }
    self.summarzingDict=[NSMutableDictionary new];
    self.backScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 80, IPHONE_WIDTH, IPHONE_HEIGHT-(80+64))];
    self.backScrollView.bounces=NO;
    self.backScrollView.showsVerticalScrollIndicator=NO;
    self.backScrollView.showsHorizontalScrollIndicator=NO;
    //self.backScrollView.backgroundColor=[UIColor blueColor];
    [self.view addSubview:self.backScrollView];
//    NSArray *imageArr=@[@"k_ic_cql2@2x",@"k_ic_qj2@2x",@"k_ic_cd2@2x",@"k_ic_zt2@2x",@"k_ic_kg2@2x",@"k_ic_wdk2@2x",@"k_ic_gc2@2x",@"k_ic_tx2@2x",@"k_ic_jb2@2x"];
    //button间隔
    CGFloat buttonWidth=IPHONE_WIDTH/2;
    CGFloat buttonHeight=buttonWidth/3*2;
    //计算scrollView内容高度
    CGFloat count=self.summarzingListModel.dataArr.count/2;
    //如果是奇数 则要多显示一行
    if (self.summarzingListModel.dataArr.count%2>0) {
        count++;
    }
    
    //设置边条
    for (int i=0; i<count; i++) {
        UILabel *line1=[[UILabel alloc]initWithFrame:CGRectMake(0, buttonHeight*i, IPHONE_WIDTH, 1)];
        line1.backgroundColor=BACKCOLOR_GRAY;
        //line1.backgroundColor=[UIColor lightGrayColor];
        [self.backScrollView addSubview:line1];
        
        if (i<1) {
            UILabel *line2=[[UILabel alloc]initWithFrame:CGRectMake(buttonWidth*(i+1),0 , 1, count*buttonHeight)];
            line2.backgroundColor=BACKCOLOR_GRAY;
            //line2.backgroundColor=[UIColor lightGrayColor];
            [self.backScrollView addSubview:line2];
        }
    }
    
    //设置内容高度
    self.backScrollView.contentSize=CGSizeMake(0, buttonHeight*count);
    for (NSInteger i=0; i<self.summarzingListModel.dataArr.count; i++) {
        SummarizingListModel *model=self.summarzingListModel.dataArr[i];
        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake(buttonWidth*(i%2), buttonHeight*(i/2), buttonWidth, buttonHeight);
        button.tag=130+i;
        //button.backgroundColor=[UIColor redColor];
        button.titleLabel.font=[UIFont systemFontOfSize:13];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //设置文字的布局
        button.titleEdgeInsets=UIEdgeInsetsMake((buttonHeight-72)/2+52, -50, 10, 0);
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        //设置图片的布局
        button.imageEdgeInsets=UIEdgeInsetsMake((buttonHeight-72)/2, (buttonWidth-52)/2,(buttonHeight-72)/2, (buttonWidth-52)/2);
        [button addTarget:self action:@selector(infoButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.backScrollView addSubview:button];
        NSString *nameStr=@"";
        NSString *imageStr=@"";
        //根据类型判断选择图片
        if ([model.totalType isEqualToString:@"ChuQ"]) {
            imageStr=@"k_ic_cql2@2x";
        }else if ([model.totalType isEqualToString:@"QingJ"]){
            imageStr=@"k_ic_qj2@2x";
        }else if ([model.totalType isEqualToString:@"ChiD"]){
            imageStr=@"k_ic_cd2@2x";
        }else if ([model.totalType isEqualToString:@"ZaoT"]){
            imageStr=@"k_ic_zt2@2x";
        }else if ([model.totalType isEqualToString:@"KuangG"]){
            imageStr=@"k_ic_kg2@2x";
        }else if ([model.totalType isEqualToString:@"WeiDK"]){
            imageStr=@"k_ic_wdk2@2x";
        }else if ([model.totalType isEqualToString:@"GongC"]){
            imageStr=@"k_ic_gc2@2x";
        }else if ([model.totalType isEqualToString:@"TiaoX"]){
            imageStr=@"k_ic_tx2@2x";
        }else if ([model.totalType isEqualToString:@"JiaB"]){
            imageStr=@"k_ic_jb2@2x";
        }
        
        nameStr=[NSString stringWithFormat:@"%@%@",model.totalName,model.totalValue];
        [button setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
        [button setTitle:nameStr forState:UIControlStateNormal];
        [self.summarzingDict setObject:button forKey:model.totalType];
        //        UILabel *title=[MyControl creatLabelWithFrame:CGRectMake(0, 60, button.width, 20) text:nameArr[i]];
        //        title.textAlignment=NSTextAlignmentCenter;
        //        [button addSubview:title];
    }
}


#pragma mark - creatTableView
- (void)creatTableView{
    if (_tableBackView) {
        return;
    }
    CGFloat height=0;
    //计算tableView的高
    if (_selectButton==1) {
        height=self.dateArr.count*44;
    }else{
        height=self.summarzingListModel.dataArr.count*44;
    }
    
    if (height>IPHONE_HEIGHT-64-80) {
        height=IPHONE_HEIGHT-64-80;
    }
    _tableBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 80, IPHONE_WIDTH, IPHONE_HEIGHT-64-80)];
//    [self.view insertSubview:_tableBackView aboveSubview:self.view];
    _tableBackView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_tableBackView];
    
    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, _tableBackView.height)];
    alphaView.alpha=0.4;
    alphaView.backgroundColor=[UIColor blackColor];
    [_tableBackView addSubview:alphaView];
    
    //点击手势
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TwoTapGestureRecognizer:)];
    tapGesture.delegate=self;
    [tapGesture setNumberOfTapsRequired:1];
    [tapGesture setNumberOfTouchesRequired:1];
    [alphaView addGestureRecognizer:tapGesture];
    
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH,height) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [_tableBackView addSubview:_tableView];
    
//    [UIView animateWithDuration:0.2 animations:^{
//        _tableBackView.y=64+80;
//    }];
    //    self.definesPresentationContext = YES;
}

#pragma mark - creatTableView
- (void)creatInfoTableView{
    if (_infoTableView) {
        return;
    }
//    CGFloat height=0;
//    //计算tableView的高
//    if (_selectButton==1) {
//        height=self.dateArr.count*44;
//    }else{
//        height=self.summarzingListModel.dataArr.count*44;
//    }
//    
//    if (height>IPHONE_HEIGHT-64-80) {
//        height=IPHONE_HEIGHT-64-80;
//    }
//    _tableBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 64+80, IPHONE_WIDTH, IPHONE_HEIGHT-64-80)];
//    [self.view insertSubview:_tableBackView aboveSubview:self.view];
//    _tableBackView.backgroundColor=[UIColor clearColor];
//    //    [self.view addSubview:_tableBackView];
//    
//    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, _tableBackView.height)];
//    alphaView.alpha=0.4;
//    alphaView.backgroundColor=[UIColor blackColor];
//    [_tableBackView addSubview:alphaView];
//    
//    //点击手势
//    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TwoTapGestureRecognizer:)];
//    tapGesture.delegate=self;
//    [tapGesture setNumberOfTapsRequired:1];
//    [tapGesture setNumberOfTouchesRequired:1];
//    [alphaView addGestureRecognizer:tapGesture];
    
    _infoTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 80, IPHONE_WIDTH,IPHONE_HEIGHT-64-80) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _infoTableView.delegate=self;
    _infoTableView.dataSource=self;
    _infoTableView.tag=111;
    _infoTableView.bounces=NO;
    _infoTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _infoTableView.showsVerticalScrollIndicator=NO;
    _infoTableView.showsHorizontalScrollIndicator=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_infoTableView];
    
    //    [UIView animateWithDuration:0.2 animations:^{
    //        _tableBackView.y=64+80;
    //    }];
    //    self.definesPresentationContext = YES;
}

#pragma mark- 搜索结果列表
- (void)creatSearchTableView{
    _searchBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 40, IPHONE_WIDTH, IPHONE_HEIGHT-64-40)];
    _searchBackView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:_searchBackView];
    
    UIView *alphaView=[[UIView alloc]initWithFrame:CGRectMake(0, 40, IPHONE_WIDTH, IPHONE_HEIGHT-64-40)];
    alphaView.alpha=0.4;
    alphaView.backgroundColor=[UIColor blackColor];
    [_searchBackView addSubview:alphaView];
    
    //点击手势
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(OneTapGestureRecognizer:)];
    tapGesture.delegate=self;
    [tapGesture setNumberOfTapsRequired:1];
    [tapGesture setNumberOfTouchesRequired:1];
    [alphaView addGestureRecognizer:tapGesture];
    
    CGFloat height=0;
    //计算tableView的高
    height=_searchListModel.dataArr.count*44;
    
    if (height>_searchBackView.height) {
        height=_searchBackView.height;
    }
    
    _searchTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, height) style:UITableViewStylePlain];
    //_searchTableView.backgroundColor=[UIColor clearColor];
    _searchTableView.delegate=self;
    _searchTableView.dataSource=self;
    _searchTableView.tag=112;
    _searchTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    //[self addTableViewUpdateRefresh:self.tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [_searchBackView addSubview:_searchTableView];
    
}

-(void)OneTapGestureRecognizer:(UIGestureRecognizer*)gr{
    
    if (_searchBackView) {
        [_searchBackView removeFromSuperview];
        _searchBackView=nil;
    }
}


#pragma mark -刷新页面数据

- (void)refreshInfoButton{
    NSString *nameStr=@"";
    NSString *imageStr=@"";
    for (NSInteger i=0; i<self.summarzingDict.allKeys.count; i++) {
        UIButton *button=[self.summarzingDict objectForKey:self.summarzingDict.allKeys[i]];
        
        if (self.summarzingListModel.dataArr.count>i) {
            SummarizingListModel *model=self.summarzingListModel.dataArr[i];
            if ([model.totalType isEqualToString:@"ChuQ"]) {
                imageStr=@"k_ic_cql2@2x";
            }else if ([model.totalType isEqualToString:@"QingJ"]){
                imageStr=@"k_ic_qj2@2x";
            }else if ([model.totalType isEqualToString:@"ChiD"]){
                imageStr=@"k_ic_cd2@2x";
            }else if ([model.totalType isEqualToString:@"ZaoT"]){
                imageStr=@"k_ic_zt2@2x";
            }else if ([model.totalType isEqualToString:@"KuangG"]){
                imageStr=@"k_ic_kg2@2x";
            }else if ([model.totalType isEqualToString:@"WeiDK"]){
                imageStr=@"k_ic_wdk2@2x";
            }else if ([model.totalType isEqualToString:@"GongC"]){
                imageStr=@"k_ic_gc2@2x";
            }else if ([model.totalType isEqualToString:@"TiaoX"]){
                imageStr=@"k_ic_tx2@2x";
            }else if ([model.totalType isEqualToString:@"JiaB"]){
                imageStr=@"k_ic_jb2@2x";
            }
            
            nameStr=[NSString stringWithFormat:@"%@%@",model.totalName,model.totalValue];
            [button setImage:[UIImage imageNamed:imageStr] forState:UIControlStateNormal];
            [button setTitle:nameStr forState:UIControlStateNormal];
        }
    }
}


-(void)TwoTapGestureRecognizer:(UIGestureRecognizer*)gr{
    
    if (_tableBackView) {
//        [UIView animateWithDuration:0.2 animations:^{
//            _tableBackView.y=64+80-(IPHONE_HEIGHT-64-80);
//        } completion:^(BOOL finished) {
            [_tableBackView removeFromSuperview];
            _tableBackView=nil;
//        }];
    }
    for (int i=0; i<_buttonArr.count; i++) {
        UIButton *button=_buttonArr[i];
        button.selected=NO;
    }
    
}

#pragma mark -搜索事件
- (void)searchClick{
    [self.view endEditing:YES];
    if (_searchTextField.text.length>0) {
        [self getDepartEmpNameRequestWithSearchtext:_searchTextField.text];
    }
}
#pragma mark -信息按钮点击
- (void)infoButtonClick:(UIButton *)button{
    //先找到button对应的key
    for (int i=0; i<_summarzingDict.allKeys.count; i++) {
        UIButton *newButton=[_summarzingDict objectForKey:_summarzingDict.allKeys[i]];
        if (newButton==button) {
            NSString *totalType=_summarzingDict.allKeys[i];
            //再遍历找到对应的model
            for (SummarizingListModel *model in _summarzingListModel.dataArr) {
                if ([model.totalType isEqualToString:totalType]) {
                    DepartmentListViewController *listView=[DepartmentListViewController new];
                    listView.itemCode=model.totalType;
                    listView.itemStr=model.totalName;
                    listView.dropListModel=self.dropListModel;
                    listView.manageModel=self.manageModel;
                    [self.navigationController pushViewController:listView animated:YES];
                    break;
                }
            }
        }
    }
}

#pragma mark -检索按钮点击

- (void)buttonClick:(UIButton *)selectButton{
    [self.view endEditing:YES];
    if (selectButton.tag==100) {//筛选页面
        PersonSelectViewController *person=[PersonSelectViewController new];
        person.manageModel=self.manageModel;
        __weak StatisticsListViewController *mySelf=self;
        person.myBlock=^(NSString *depOrEmp,NSString *personStr,NSString *departStr){
            mySelf.depOrEmp=[depOrEmp copy];
            mySelf.empId=[personStr copy];
            mySelf.memberNames=[departStr copy];
            [mySelf getSummarizingListRequest];
        };
        [self.navigationController pushViewController:person animated:YES];
    }else if (selectButton.tag==103){//切换
        selectButton.selected=!selectButton.selected;
        //根据开关状态 是否打开选择页面
        if (selectButton.selected) {
            if (!self.infoTableView) {
                [self creatInfoTableView];
            }
            //                [self refreshSelectViewWithSelectNum:selectButton.tag-100];
        }else{
            [_infoTableView removeFromSuperview];
            _infoTableView=nil;
        }
    }else{
        UIButton *button1=(UIButton *)[selectButton.superview viewWithTag:101];
        UIButton *button2=(UIButton *)[selectButton.superview viewWithTag:102];
        selectButton.selected=!selectButton.selected;
        if (selectButton.selected) {
            _selectButton=selectButton.tag-100;
            //如果没有则创建  如果有则刷新
            if (!_tableBackView) {
                [self creatTableView];
            }else{
                CGFloat height=0;
                //计算tableView的高
                if (_selectButton==1) {
                    height=self.dateArr.count*44;
                }else{
                    height=self.summarzingListModel.dataArr.count*44;
                }
                
                if (height>IPHONE_HEIGHT-64-80) {
                    height=IPHONE_HEIGHT-64-80;
                }
                _tableView.height=height;
                [_tableView reloadData];
            }
            if (button1==selectButton) {
                button2.selected=NO;
            }else{
                button1.selected=NO;
            }
        }else{
            [_tableBackView removeFromSuperview];
            _tableBackView=nil;
        }
    }
}


#pragma mark -textFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self addTapGestureRecognizerWithView:self.view];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    [self removeTapGestureRecognizerWithView:self.view];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    if (_searchTextField.text.length>0) {
        //[self getDutyFlowListRequestWithState:@"0"];
    }
    return YES;
}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag==111) {
        return self.summarzingListModel.dataArr.count;
    }else if (tableView.tag==112){
        return _searchListModel.dataArr.count;
    }else{
        if (_selectButton==1) {
            return self.dateArr.count;
        }else if (_selectButton==2){
            return _dropListModel.dataArr.count;
        }
    }
    return 0;
    //return _newsListModel.dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag==110) {
        //筛选条件
        NSString *cellID=@"StatisticsTableViewCell";
        StatisticsTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell=[[StatisticsTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
            //        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        if (_selectButton==1) {
            cell.messageLabel.text=self.dateArr[indexPath.row];
        }
        if (_selectButton==2) {
            DutyDropListModel *model=_dropListModel.dataArr[indexPath.row];
            cell.messageLabel.text=model.keyword;
        }
        return cell;
    }else if(tableView.tag==111){
        //汇总信息
        NSString *cellID=@"InfoListTableViewCell";
        InfoListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell=[[InfoListTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
            //        cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
        }
        SummarizingListModel *model=_summarzingListModel.dataArr[indexPath.row];
        cell.myTitleLabel.text=model.totalName;
        cell.maxMessageLabel.text=[NSString stringWithFormat:@"最高:%@",model.totalMaxValue.length>0?model.totalMaxValue:@"--"];
        //如果有数据才拼接
        if (model.totalMaxMember.length>0) {
            cell.maxMessageLabel.text=[cell.maxMessageLabel.text stringByAppendingString:[NSString stringWithFormat:@"(%@)",model.totalMaxMember]];
        }
        cell.minMessageLabel.text=[NSString stringWithFormat:@"最低:%@",model.totalMinValue.length>0?model.totalMinValue:@"--"];
        if (model.totalMinMember.length>0) {
            cell.minMessageLabel.text=[cell.minMessageLabel.text stringByAppendingString:[NSString stringWithFormat:@"(%@)",model.totalMinMember]];
        }
        cell.countLabel.text=model.totalValue;
        return cell;
    }else{
        //搜索结果列表
        NSString *cellID=@"CenterLabelTableViewCell";
        CenterLabelTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell=[[CenterLabelTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
            cell.selectionStyle=UITableViewCellSelectionStyleDefault;
            UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(0, 43, IPHONE_WIDTH, 1)];
            line.backgroundColor=BACKCOLOR_GRAY;
            [cell.contentView addSubview:line];
        }
        AddressSearchModel *searchModel=_searchListModel.dataArr[indexPath.row];
        cell.myTitle.text=[NSString stringWithFormat:@"%@(%@)",searchModel.respName,[searchModel.isDepart isEqualToString:@"0"]?@"个人":@"部门"];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //计算内容的宽和高
//    if (_selectButton==2) {
//        return 44;
//    }
    if (tableView.tag==111) {
        return 56;
    }
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag==110) {
        //时间段选择
        if (_selectButton==1) {
            //self.dateArr=@[@"本月",@"上月",@"本季度",@"上季度",@"上半年",@"下半年"];
            if ([_dateArr[indexPath.row] isEqualToString:@"本月"]) {
                self.beginStr=[LZXHelper getFirstDayInMonth];
                self.endStr=[LZXHelper getLastDayInMonth];
            }else if ([_dateArr[indexPath.row] isEqualToString:@"上月"]) {
                self.beginStr=[LZXHelper getFirstDayInLastMonth];
                self.endStr=[LZXHelper getLastDayInLastMonth];
            }else if ([_dateArr[indexPath.row] isEqualToString:@"本季度"]) {
                self.beginStr=[LZXHelper getFirstDayWithQuarter];
                self.endStr=[LZXHelper getLastDayWithQuarter];
            }else if ([_dateArr[indexPath.row] isEqualToString:@"上季度"]) {
                self.beginStr=[LZXHelper getFirstDayWithLastQuarter];
                self.endStr=[LZXHelper getLastDayWithLastQuarter];
            }else if ([_dateArr[indexPath.row] isEqualToString:@"上半年"]) {
                self.beginStr=[LZXHelper getFirstDayWithFirstHalfAYear];
                self.endStr=[LZXHelper getLastDayWithFirstHalfAYear];
            }else if ([_dateArr[indexPath.row] isEqualToString:@"下半年"]) {
                self.beginStr=[LZXHelper getFirstDayWithSecondHalfAYear];
                self.endStr=[LZXHelper getLastDayWithSecondHalfAYear];
            }
            [self getSummarizingListRequest];
            //将选择的显示到button上
            UIButton *button=_buttonArr[_selectButton];
            [button setTitle:_dateArr[indexPath.row] forState:UIControlStateNormal];
        }else{
        //信息类型选择
            
            DutyDropListModel *model=self.dropListModel.dataArr[indexPath.row];
            //将选择的显示到button上
            UIButton *button=_buttonArr[_selectButton];
            [button setTitle:model.keyword forState:UIControlStateNormal];
            DepartmentListViewController *listView=[DepartmentListViewController new];
            listView.itemCode=model.keywordId;
            listView.itemStr=model.keyword;
            listView.dropListModel=self.dropListModel;
            listView.manageModel=self.manageModel;
            [self.navigationController pushViewController:listView animated:YES];
        }
        //点击后开始请求数据 并移除view 重置按钮状态
        [_tableBackView removeFromSuperview];
        _tableBackView=nil;
        for (int i=0; i<_buttonArr.count; i++) {
            UIButton *button=_buttonArr[i];
            if (i==1||i==2) {
                button.selected=NO;
            }
        }
    }else if(tableView.tag==111){
        SummarizingListModel *model=self.summarzingListModel.dataArr[indexPath.row];
        DepartmentListViewController *listView=[DepartmentListViewController new];
        listView.itemCode=model.totalType;
        listView.itemStr=model.totalName;
        listView.dropListModel=self.dropListModel;
        listView.manageModel=self.manageModel;
        
        [self.navigationController pushViewController:listView animated:YES];
    }else{
        AddressSearchModel *searchModel=_searchListModel.dataArr[indexPath.row];
        //如果是部门
        if ([searchModel.isDepart isEqualToString:@"1"]) {
            self.memberNames=searchModel.respId;
            [self getSummarizingListRequest];
        }else{
            //如果是个人
            PersonInfoDetailViewController *person=[PersonInfoDetailViewController new];
            person.empIds=searchModel.respId;
            [self.navigationController pushViewController:person animated:YES];
        }
        //搜索的时候移除掉searchBackView
        if (_searchBackView) {
            [_searchBackView removeFromSuperview];
            _searchBackView=nil;
        }
    }
}

#pragma mark -模糊查询条件
- (void)getDepartEmpNameRequestWithSearchtext:(NSString *)searchText{
    NSDictionary *dict=@{
                         @"inputValue":searchText,
                         @"isDepartOrEmp":@"2",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:[[UIApplication sharedApplication].delegate window]];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getDepartEmpName soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
        
        //解析数据
        _searchListModel=[[AddressSearchModel alloc]initWithResponse:responseObject];
        if ([_searchListModel.code isEqualToString:@"200"]) {
            if (!_searchBackView) {
                [self creatSearchTableView];
            }else{
                CGFloat height=0;
                //计算tableView的高
                height=_searchListModel.dataArr.count*44;
                
                if (height>_searchBackView.height) {
                    height=_searchBackView.height;
                }
                _searchTableView.height=height;
                [_searchTableView reloadData];
            }
            if (_searchListModel.dataArr.count==0) {
                //增加提示语
                [self addReminderViewWithFrame:_searchTableView.frame msg:@"没有搜索到该员工！" backView:_searchTableView];
            }else{
                //移除提示语
                [self removeReminderView];
            }
        }else if([_searchListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:_searchListModel.msg View:self.view];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
    }];
}

#pragma mark -获取可选项列表
- (void)getDropListRequestWithdataSwith:(NSString *)dataSwith{
    if (!self.itemArr) {
        self.itemArr=[NSMutableArray new];
    }
    NSDictionary *dict=@{
                         @"dataSwith":dataSwith?dataSwith:@"",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    //[LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:[[UIApplication sharedApplication].delegate window]];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getDropList soapBody:soap success:^(id responseObject) {
        //[LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
        
        //解析数据
        self.dropListModel=[[DutyDropListModel alloc]initWithResponse:responseObject];
        if ([self.dropListModel.code isEqualToString:@"200"]) {
            
//            for (DutyDropListModel *model in self.dropListModel.dataArr) {
//                [self.itemArr addObject:model.keywordId];
//            }
//            [self getSummarizingListRequestWithBeginTime:[LZXHelper getFirstDayInMonth] endTime:[LZXHelper getLastDayInMonth]];
        }else if([self.dropListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:self.dropListModel.msg View:[[UIApplication sharedApplication].delegate window]];
        }
    } failure:^(NSError *error) {
        //[LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
    }];
}

#pragma mark -获取汇总信息
- (void)getSummarizingListRequest{
//    NSString *itemStr=[self.itemArr componentsJoinedByString:@","];
    NSDictionary *dict=@{
                         @"beginTime":self.beginStr?self.beginStr:@"",
                         @"endTime":self.endStr?self.endStr:@"",
                         @"depOrEmp":self.depOrEmp?self.depOrEmp:@"1",
                         @"empIds":self.empId?self.empId:@"",
                         @"memberNames":self.memberNames?self.memberNames:@"1",
                         };
    
    //   字典转json
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    //拼接soap字符串
    NSString* soap = [NSString stringWithFormat:@"<sessionId>%@</sessionId>\n<content>%@</content>",[LZXHelper getSessionID],str];
    // __weak AddressBookViewController *mySelf=self;
    [LZXHelper postLoadViewWithText:HUD_PLEASEWAIT View:[[UIApplication sharedApplication].delegate window]];
    [HttpRequest SOAPData:[LZXHelper getServerURL] SoapMthod:getSummarizingList soapBody:soap success:^(id responseObject) {
        [LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
        
        //解析数据
        self.summarzingListModel=[[SummarizingListModel alloc]initWithResponse:responseObject];
        if ([self.summarzingListModel.code isEqualToString:@"200"]) {
            //如果有先移除
            if (!self.backScrollView) {
                //页面汇总信息按钮
                [self creatFunctionButtonView];
            }else{
                [self refreshInfoButton];
            }

            if (_infoTableView) {
                [_infoTableView reloadData];
            }
        }else if([self.summarzingListModel.code isEqualToString:@"220"]){
            [LZXHelper postMessageWithText:self.summarzingListModel.msg View:[[UIApplication sharedApplication].delegate window]];
        }
    } failure:^(NSError *error) {
        [LZXHelper hideLoadViewWithView:[[UIApplication sharedApplication].delegate window]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
